﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HTTT.Bussiness;
using HTTT.DataAccess;
using HTTT.Utilities;
using System.Configuration;
using HTTT.AD;

namespace HTTT.admin
{
    public partial class EditUser : System.Web.UI.Page
    {
        /// <summary>
        ///  View State Username
        /// </summary>
        private string Username
        {
            get
            {
                object obj = this.ViewState["_Username"];
                if (obj == null)
                    return ""; //default to show ID : 0 
                else
                    return (string)obj;
            }
            set
            {
                this.ViewState["_Username"] = value;
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            Username = Request.QueryString["ID"];
            HT_UserBO UserBO = new HT_UserBO();
            if (Username != "")
            {
                string ouPath = LoadUserDetail(Username);
                LoadOU(ouPath);
            }
            else
            {
                Response.Redirect("UserList.aspx");
            }
        }
        private void LoadOU(string selectedValue)
        {
            //Get OU list
            HT_OUBO Bo = new HT_OUBO();
            List<HT_OU> ListBO = Bo.GetAllHT_OU().ToList();
            ddlOU.DataSource = ListBO;
            ddlOU.DataValueField = ADOUProperties.DISTINGUISHEDNAME;
            ddlOU.DataTextField = ADOUProperties.NAME;
            ddlOU.DataBind();
            ddlOU.Items.Insert(0, new ListItem("▼ " + ConfigurationManager.AppSettings["LDAPDomain"], ConfigurationManager.AppSettings["DomainPath"]));
            ddlOU.SelectedValue = selectedValue;
        }
        private string LoadUserDetail(string username)
        {
            //Get UserInfo by username
            HT_UserDAO dao = new HT_UserDAO();
            HT_User UserInfo = dao.GetHT_UserByUsername(username);
            txtgivenName.Text = UserInfo.givenName;
            txtmidleName.Text = UserInfo.initials;
            txtsurName.Text = UserInfo.sn;
            txtDisplayName.Text = UserInfo.displayName;
            txtDescription.Text = UserInfo.description;
            txtMail.Text = UserInfo.mail;
            txtHomePage.Text = UserInfo.wWWHomePage;
            txtUserName.Text = UserInfo.sAMAccountName;
            txtJob.Text = UserInfo.title;
            txtPhysicalDeliveryOfficeName.Text = UserInfo.physicalDeliveryOfficeName;
            txtCompany.Text = UserInfo.company;
            txtDepartment.Text = UserInfo.department;
            txtAddress1.Text = UserInfo.streetAddress;
            txtAddress2.Text = UserInfo.postOfficeBox;
            txtPostalcode.Text = UserInfo.postalCode;
            txtCity.Text = UserInfo.l;
            txtProvince.Text = UserInfo.st;
            txtCountry.Text = UserInfo.c;
            txtHomephone.Text = UserInfo.homephone;
            txtMobile.Text = UserInfo.mobile;
            txtOfficephone.Text = UserInfo.voiceTelephoneNumber;
            txtFax.Text = UserInfo.facsimileTelephoneNumber;
            txtIpphone.Text = UserInfo.ipPhone;
            //txtNote.Text = UserInfo.info;
            long AccountOptions = (long)UserInfo.userAccountControl;
            foreach (ListItem i in chklAccountOptions.Items)
            {
                if ((AccountOptions & Convert.ToInt64(i.Value)) > 0)
                {
                    i.Selected = true;
                }
            }
            string ouPath = UserInfo.distinguishedName;
            ouPath = ouPath.Substring(ouPath.IndexOf(',') + 1);
            return ouPath;
        }


        protected void btnResetPwd_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                HT_UserBO bo = new HT_UserBO();
                bool result = bo.ResetPwdUser(Username, Page.User.Identity.Name, txtFromRequest.Text);
                if (result)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatAlertMsg("Tạo yêu cầu đặt lại mật khẩu thành công !"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                SaveForm();
                ////TODO: Show msg
                Response.Redirect("EditUser.aspx?ID=" + Username);
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
        }


        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                if (SaveForm())
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatMsgThenRedirect("Tạo yêu cầu sửa thành công", "UserList.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }
        protected void btnSaveNew_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                if (SaveForm())
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", Common.FormatMsgThenRedirect("Tạo yêu cầu sửa thành công", "AddUser.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserList.aspx");
        }
        protected void btnDisable_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                HT_UserBO bo = new HT_UserBO();
                bool result = bo.BlockUser(Username, Page.User.Identity.Name, txtFromRequest.Text);
                if (result)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatMsgThenRedirect("Tạo yêu cầu khóa tài khoản thành công !", "UserList.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }
        protected void btnEnable_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                HT_UserBO bo = new HT_UserBO();
                bool result = bo.UnBlockUser(Username, Page.User.Identity.Name, txtFromRequest.Text);
                if (result)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatMsgThenRedirect("Tạo yêu cầu mở khóa tài khoản thành công !", "UserList.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }
        

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ReturnValue<bool> Valid = ValidateData();
            if (Valid.RetValue)
            {
                HT_UserBO bo = new HT_UserBO();
                bool result = bo.DeleteUser(Username, Page.User.Identity.Name, txtFromRequest.Text);
                if (result)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatMsgThenRedirect("Tạo yêu cầu xóa tài khoản thành công !", "UserList.aspx"), true);
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "Message", Common.FormatAlertMsg(Valid.Msg), true);
            }
            
        }

        private ReturnValue<bool> ValidateData()
        {
            if (txtFromRequest.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập thông tin yêu cầu");
            if (txtgivenName.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập Họ người dùng");
            if (txtsurName.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập Tên người dùng");
            if (txtUserName.Text.Trim() == string.Empty) return new ReturnValue<bool>(false, "Phải nhập Tên người dùng");
            if (ddlOU.SelectedIndex == 0) return new ReturnValue<bool>(false, "Phải chọn OU");

	        return new ReturnValue<bool>(true, "");
        }


        private bool SaveForm()
        {
            //Collec infomation
            HT_Request NewRequest = new HT_Request();
            HT_UserBO userBO = new HT_UserBO();
            NewRequest.ID = Guid.NewGuid();
            NewRequest.Action = HT_ACTION.EDIT_USER.ToString();
            String distigutedName = "CN=" + txtDisplayName.Text.Trim() + ",";
            distigutedName += ddlOU.SelectedValue;
            long AccountOptions = 512;
            foreach (ListItem i in chklAccountOptions.Items)
            {
                if (i.Selected)
                {
                    AccountOptions += Convert.ToInt64(i.Value);
                }
            }
            NewRequest.ActionDescription = userBO.BuildEditUserString(
                                        txtgivenName.Text
                                        , txtmidleName.Text
                                        , txtsurName.Text
                                        , txtDisplayName.Text
                                        , txtDescription.Text
                                        , txtMail.Text
                                        , txtHomePage.Text
                                        , txtJob.Text
                                        , txtPhysicalDeliveryOfficeName.Text
                                        , txtCompany.Text
                                        , txtDepartment.Text
                                        , null  //manager
                                        , txtAddress1.Text
                                        , txtAddress2.Text
                                        , txtCity.Text
                                        , txtPostalcode.Text
                                        , txtProvince.Text
                                        , txtCountry.Text
                                        , txtHomephone.Text
                                        , txtOfficephone.Text
                                        , txtMobile.Text
                                        , txtFax.Text
                                        , txtIpphone.Text
                                        , txtNote.Text
                                        , txtUserName.Text
                                        , txtUserName.Text + "@" + ConfigurationManager.AppSettings["LDAPDomain"]
                                        , distigutedName
                                        , AccountOptions
                                        , DateTime.Now
                                        , null
                                        , DateTime.Now
                                        , DateTime.Now);
            string OUName = ddlOU.SelectedItem.Text;
            OUName = OUName.Substring(OUName.IndexOf("├ ") + 1);
            NewRequest.ActionName = "Sửa tài khoản <strong>" + txtUserName.Text + "</strong>";
            NewRequest.Status = Utilities.HT_REQUESTSTATUS.PEDDING.ToString();
            NewRequest.Note = txtFromRequest.Text.Trim();
            NewRequest.RequestDate = DateTime.Now;
            NewRequest.Requestedby = Page.User.Identity.Name;
            HT_RequestBO re = new HT_RequestBO();
            Boolean result = re.InsertRequest(NewRequest);
            return result;
        }
    }
}